package cn.xawl.gulimall.auth.controller;

import cn.xawl.common.constant.MemberConstant;
import cn.xawl.common.constant.SmsTemplateConstant;
import cn.xawl.common.exception.BizCodeEnum;
import cn.xawl.common.utils.NumberUtils;
import cn.xawl.common.utils.R;
import cn.xawl.common.vo.MemberVo;
import cn.xawl.gulimall.auth.feign.MemberFeign;
import cn.xawl.gulimall.auth.feign.ThirdPartyFeign;
import cn.xawl.gulimall.auth.vo.UserInfoVo;
import cn.xawl.gulimall.auth.vo.UserLoginVo;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lh
 * @create 2020-10-30 16:32
 **/
@Controller
public class AuthController {

    @Autowired
    private ThirdPartyFeign thirdPartyFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeign memberFeign;

    @GetMapping("/login.html")
    public String login(HttpSession session) {
        if (session.getAttribute(MemberConstant.LOGIN_USER) == null) {
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }
    }


    @ResponseBody
    @GetMapping("/auth/send/register/sms")
    public R sendLoginSms(@RequestParam String telephone) {

        String redisCode = redisTemplate.opsForValue().get(telephone);
        if (!StringUtils.isEmpty(redisCode)) {
            String[] s = redisCode.split("_");
            long saveCodeTime = Long.parseLong(s[1]);
            if (System.currentTimeMillis() - saveCodeTime < 60000) {
                //发送事件如果小于一分钟，就返回异常
                return R.error(BizCodeEnum.SEND_SMS_EXCEPTION.getCode(), BizCodeEnum.SEND_SMS_EXCEPTION.getMsg());
            }
        }
        String code = NumberUtils.generateCode(6);
        thirdPartyFeign.sendSms(telephone, code, SmsTemplateConstant.LOGIN_TEMPLATE.getTemplate());
        return R.ok();
    }

    @PostMapping("/auth/register")
    public String register(@Validated UserInfoVo userInfo, BindingResult result, RedirectAttributes redirectAttributes) {

        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors()
                    .stream()
                    .collect(Collectors.toMap(FieldError::getField, v -> {
                        if (StringUtils.isEmpty(v.getDefaultMessage())) {
                            return "";
                        }
                        return v.getDefaultMessage();
                    }, (v1, v2) -> v1 + "," + v2));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/register.html";
        }

        Map<String, String> errors = new HashMap<>(); //
        //注册信息无误，验证验证码
        String redisCode = redisTemplate.opsForValue().get(userInfo.getTelephone());
        if (!StringUtils.isEmpty(redisCode)) {
            String[] s = redisCode.split("_");
            String savedCode = s[0];
            if (userInfo.getCode().equals(savedCode)) {
                //验证通过，删除当前验证码
                redisTemplate.delete(userInfo.getTelephone());
                //调用远程会员服务进行添加用户操作
                R r = memberFeign.register(userInfo);
                if ((int)r.get("code") != 0) {
                    //如果没有调用成功，重新注册
                    errors.put("msg", r.getData(new TypeReference<String>(){}, "msg"));
                    return "redirect:http://auth.gulimall.com/register.html";
                }
                //转到登陆界面
                return "redirect:http://auth.gulimall.com/login.html";
            } else {
                //验证码错误
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/register.html";
            }

        } else {
            //验证码不存在
            errors.put("code", "请先发送验证码");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/register.html";
        }

    }


    @PostMapping("/auth/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session) {

        R r = memberFeign.login(userLoginVo);
        if ((int)r.get("code") == 0) {
            session.setAttribute(MemberConstant.LOGIN_USER, r.getData(new TypeReference<MemberVo>(){}));
            return "redirect:http://gulimall.com";
        } else {
            redirectAttributes.addFlashAttribute("msg", r.get("msg"));
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

}
